package com.fitness.servlet;

import com.fitness.dao.MemberDAO;
import com.fitness.entity.Member;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private final MemberDAO memberDAO = new MemberDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userType = request.getParameter("userType");
        String memberIdStr = request.getParameter("memberId");

        // 1. 处理管理员登录（无需验证，直接跳转）
        if ("admin".equals(userType)) {
            response.sendRedirect("adminHome.html"); // 管理员页面通常不在WEB-INF下，可直接重定向
            return;
        }

        // 2. 处理会员登录（需验证ID）
        if ("member".equals(userType)) {
            // 验证会员ID是否为空
            if (memberIdStr == null || memberIdStr.isEmpty()) {
                request.setAttribute("error", "请输入会员ID");
                request.getRequestDispatcher("index.jsp").forward(request, response);
                return;
            }

            try {
                int memberId = Integer.parseInt(memberIdStr);
                Member member = memberDAO.getMemberById(memberId);

                if (member == null) {
                    request.setAttribute("error", "会员ID不存在");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                    return;
                }

                // 登录成功，保存会员信息到会话
                HttpSession session = request.getSession();
                session.setAttribute("member", member);

                response.sendRedirect("ReservationServlet");
            } catch (NumberFormatException e) {
                request.setAttribute("error", "会员ID必须为数字");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("error", "无效的用户类型");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}